//
//  LTMainSceneryController.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-29.
//  Copyright (c) 2014年 jxw. All rights reserved.
//
#define RecordsOfPage 20
#define advHeight 100
#import "LTMainSceneryController.h"

@interface LTMainSceneryController ()
{
     NSMutableArray* _arrayScenery;
    UIActivityIndicatorView  *_activity;
    
    CLLocationManager *_currentLoaction;
    
    NSUserDefaults *myDefaults;
    UICollectionView* _collectionView;
    

    NSString* _currentCityID;//当前城市ID
   NSString* _currentCityName;//当前城市ID
    NSString* _keyWord;
    LTAppDelegate* _appDelegate;
    
    int _currentPage;//当前页数
    int _totalPage;
    BOOL _blKeyWordSearch;
     UIStoryboard *_storyBoard;
     GADBannerView* bannerView_;
    
    MobiSageAdBanner * adBanner;
}
@end

@implementation LTMainSceneryController
- (UIViewController *)viewControllerToPresent
{
    return self;
}
-(void)addSageAd{
    adBanner = [[MobiSageAdBanner alloc] initWithAdSize:Ad_320X50 withDelegate:self];
    adBanner.frame = CGRectMake(0, 0, 320, 50);
    [adBanner setInterval:Ad_Refresh_30];
    //设置广告轮播动画效果
    [adBanner setSwitchAnimeType:Random];
    
    [self.collectionView addSubview:adBanner];
}
-(void)addGoogleAdv{
  
    bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            0.0 ,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];    // 指定广告单元ID。
    
    bannerView_.adUnitID = [CommonConfigUtil getGoogleAdvId];
    
    bannerView_.rootViewController = self;
    [self.collectionView addSubview:bannerView_];
    GADRequest *request = [GADRequest request];
    // request.testDevices = @[ GAD_SIMULATOR_ID ];
    [bannerView_ loadRequest:request];
}
-(void)btnCancelClicked:(id)sender{
    self.navigationItem.leftBarButtonItems=[NSArray arrayWithObject:self.btnSearch];
    self.navigationItem.title=_currentCityName;
    
    if(_blKeyWordSearch){
         _blKeyWordSearch=NO;
      _keyWord=@"";
      _currentPage=0;
      _totalPage=0;
      [_arrayScenery removeAllObjects];
       [self loadData];
       
    }
    
}
- (IBAction)btnSearchClicked:(UIBarButtonItem *)sender {
    
    self.navigationItem.title=@"";
    //UIView* viewSearch=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 190, 30)];
    
      UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    
      searchBar.placeholder=@"输入景点名称";
      searchBar.delegate=self;
    UIBarButtonItem* item=[[UIBarButtonItem alloc]initWithCustomView:searchBar];
    UIBarButtonItem *btnCancel=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(btnCancelClicked:)];
    self.navigationItem.leftBarButtonItems=[NSArray arrayWithObjects:item,btnCancel, nil];
  
      item=nil;
      searchBar=nil;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    [searchBar resignFirstResponder];   //隐藏输入键盘
    
    if(![searchBar.text isEqualToString:@""]){
        _blKeyWordSearch=YES;
        _keyWord=searchBar.text;
        _currentPage=0;
        _totalPage=0;
        [_arrayScenery removeAllObjects];
        [self loadData];
    }

    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
   
    
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _arrayScenery=[[NSMutableArray alloc] init];
    _currentPage=0;
    _totalPage=0;
    _appDelegate=[[UIApplication sharedApplication] delegate];
    myDefaults=[NSUserDefaults standardUserDefaults];
    _currentCityName=@"全国";
    self.navigationItem.title=_currentCityName;
    [self startGetLocation];
    
    self.view.backgroundColor=BACKGROUND_COLOR;
    self.collectionView.backgroundColor=[UIColor clearColor];
   [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionCell" bundle:nil] forCellWithReuseIdentifier:@"CollectionCell"];
    [self loadData];
    
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkVersionTimer:) userInfo:nil repeats:NO];
   
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if(adBanner==nil){
      [self addSageAd];
    }
    
    /*
    if(bannerView_ ==nil){
     [self addGoogleAdv];
    }*/
    
}

-(void)startGetLocation{
    _currentLoaction = [[CLLocationManager alloc] init];
    _currentLoaction.delegate = self;
    
    _currentLoaction.distanceFilter = 1000;
    
    _currentLoaction.desiredAccuracy = kCLLocationAccuracyBest;
    [_currentLoaction startUpdatingLocation];
}

-(void) checkVersionTimer:(NSTimer*)theTimer{
    [self checkVersion];
    [theTimer invalidate];
}



-(void)checkVersion{
    
    if([CommonConfigUtil checkVersion]){
        
        NSString *versionNumber=[myDefaults objectForKey:@"versionNumber"];
        NSString *appUrl=[myDefaults objectForKey:@"appUrl"];
        // NSString *appCommentUrl=[myDefaults objectForKey:@"appCommentUrl"];
        NSString *description=[myDefaults objectForKey:@"description"];
        
        if(nil==appUrl)appUrl=@"";
        if(nil==versionNumber)versionNumber=@"";
        if(nil==description)description=@"";
        
        
        if(![@"" isEqualToString:appUrl] && nil!=versionNumber&& ![@"" isEqualToString:versionNumber]&& [versionNumber compare: [CommonConfigUtil getCurrVersion] ]==NSOrderedDescending ){
            
            
            NSString *strMessge;
            if(nil!=description&&![@"" isEqualToString:description]){
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！%@",versionNumber,description];
            }else{
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！是否需要升级？",versionNumber];
            }
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本升级" message:strMessge                                                           delegate:self  cancelButtonTitle:@"立即升级" otherButtonTitles: @"忽略",nil];
            [alert setTag:1];
            
            [alert show];
            
            alert=nil;
        }
        
    }
    
}




- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if([alertView tag]==1&&buttonIndex == 0) {
        
        NSString *appUrl=  [myDefaults objectForKey:@"appUrl"];
        if(nil!=appUrl && ![@"" isEqualToString:appUrl]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrl]];
        }
        
    }
    
}



- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [_currentLoaction stopUpdatingLocation];
    
    _appDelegate.currentPostionlatitude=newLocation.coordinate.latitude;
    _appDelegate.currentPostionlongitude=newLocation.coordinate.longitude;
    BOOL  __block hasCity=NO;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if(placemarks.count>0){
            CLPlacemark* _placeMark = [placemarks objectAtIndex:0];
            
            NSLog(@"%@",_placeMark.locality);
            self.navigationItem.title=_placeMark.locality;
            [self searchSceneryByCityName:_placeMark.locality];
            hasCity=YES;
        }
        // we have received our current location, so enable the "Get Current Address" button
    }];
    geocoder=nil;
    _currentLoaction=nil;
    if(!hasCity){
        //读取北京的景点
        
        
        // _currentCityID=@"53";
        // [self searchSceneryByCityID:_currentCityID page:1 pageSize:RecordsOfPage];
    }
}
-(void)searchSceneryByCityName:(NSString*)cityName{
    
    if([cityName hasSuffix:@"市"]) {
        cityName=[cityName substringToIndex:cityName.length -1];
    }
    NSString* cityID=[_appDelegate getCityIDByName:cityName];
    _currentCityID =cityID;
    _currentCityName=cityName;
    _appDelegate.currentCityName=cityName;
    _appDelegate.currentCityID=cityID;
    [self searchSceneryByCityID:cityID page:1 pageSize:RecordsOfPage];
    
    
    
}
-(void)createActivityIndicatorView{
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	_activity.center = self.view.center;
	_activity.hidesWhenStopped = TRUE;
	[self.view addSubview:_activity];
	[_activity startAnimating];

}
-(void)removeActivityIndicatorView{
    [_activity stopAnimating];
    [_activity removeFromSuperview];
}
-(void)searchSceneryByCityID:(NSString*)cityID page:(int)page pageSize:(int)pageSize{
   
    [self createActivityIndicatorView];
    

    //为空则读取北京的景点
    if(cityID ==nil )
    {
        cityID=@"";
    }

    NSDictionary* dict3=[NSDictionary dictionaryWithObjectsAndKeys:cityID,@"cityID",[NSString stringWithFormat:@"%d",page],@"page",[NSString stringWithFormat:@"%d",pageSize],@"pageSize",_keyWord,@"keyWord", nil];
    
    
        [NSThread detachNewThreadSelector:@selector(searchSceneryByCityIDInBackgroud:) toTarget:self withObject:dict3];
}

-(void)searchSceneryByCityIDInBackgroud:(NSDictionary*)dict{
    
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    NSString* cityID=[dict objectForKey:@"cityID"];
 
    
    NSString* page=[dict objectForKey:@"page"];
    NSString* pageSize=[dict objectForKey:@"pageSize"];
    NSString* keyWord=[dict objectForKey:@"keyWord"];
    
   // NSString* xmlData= [LocalTravelRequest getSceneryListByCityId:cityID page:[page intValue] pageSize:[pageSize intValue]];
    
    
    NSString* xmlData= [LocalTravelRequest searchScenery:cityID themeId:@"" keyWord:keyWord longitude:@"" latitude:@"" radius:0 page:[page intValue] pageSize:[pageSize intValue]];
    [self performSelectorOnMainThread:@selector(parseData:) withObject:xmlData waitUntilDone:NO];
    //[self parseData:xmlData  cityID:cityID];
    
    
    
    
}
-(void) parseData:(NSString*)xmlData{
    SceneryListParse* parse=[[SceneryListParse alloc]initWithXmlData:xmlData];
    
    NSMutableDictionary* dictRet=[parse getScenaryList];
    if(dictRet!=nil){
        
      NSString* strTotalPage  =[dictRet objectForKey:@"totalPage"];
        _totalPage=[strTotalPage intValue];
        
       NSMutableArray* newArray=[dictRet objectForKey:@"sceneryArray"];
    
       parse=nil;
       if( _arrayScenery.count==0){
          [_arrayScenery addObjectsFromArray:newArray];
           [self.collectionView reloadData];
       }else{
           int count=_arrayScenery.count;
           [self.collectionView performBatchUpdates:^{
              [_arrayScenery addObjectsFromArray:newArray];
               
               NSMutableArray* arrayIndexPath=[NSMutableArray array];
               for (int i=0; i<newArray.count; i++) {
                   
                   [arrayIndexPath addObject:[NSIndexPath indexPathForItem:count+i inSection:0]];
               }
              // [self.collectionView reloadData];
               [self.collectionView insertItemsAtIndexPaths:arrayIndexPath];
               
           } completion:nil];
           
           
       }
    
        
   }
    [self removeActivityIndicatorView];
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(_arrayScenery !=nil) return _arrayScenery.count;
    
    return 0;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
	return CGSizeMake(134,152);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
    if(_arrayScenery !=nil && _arrayScenery.count>indexPath.row){
        NSDictionary* dict=[_arrayScenery objectAtIndex:indexPath.row];
        cell.lblTitle.text=[dict objectForKey:@"sceneryName"];
        cell.lblPrice.text=[NSString stringWithFormat:@"最低价:¥ %@",[dict objectForKey:@"amountAdv"]];
        
        
        // cell.imageView.imageUrl=[dict objectForKey:@"imgPath"];
        NSString* imageName=[dict objectForKey:@"imgPath"];
        
        NSString* netImagePath=[NSString stringWithFormat:@"%@160_120/%@",[CommonConfigUtil getTongChenImageBaseUrl],imageName];
        cell.imageView.imageUrl=netImagePath;
        //cell.imageView.imageUrl=netImagePath;
        //cell.imageView.im
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(_arrayScenery ==nil || _arrayScenery.count<indexPath.row) return ;
    
    if(_storyBoard==nil){
        _storyBoard=[UIStoryboard storyboardWithName:@"second" bundle:nil];
    }
  UINavigationController* navi=   [_storyBoard instantiateViewControllerWithIdentifier:@"NaviDetailController"];
   
    LTSceneryDetailController* vc=[navi.viewControllers objectAtIndex:0];
    vc.dictScenery=[_arrayScenery objectAtIndex:indexPath.row];
   // NSString* des=[vc.dictScenery objectForKey:@"scenerySummary"];
    [self presentViewController:navi animated:YES completion:nil];
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(60, 15, 15, 15);
}

- (void)scrollViewDidScroll:(UIScrollView*)scrollViewDrag {
    
    CGPoint offset = self.collectionView.contentOffset;
    CGRect bounds = self.collectionView.bounds;
    CGSize size = self.collectionView.contentSize;
    UIEdgeInsets inset = self.collectionView.contentInset;
    CGFloat currentOffset = offset.y + bounds.size.height -inset.bottom;
    CGFloat maximumOffset = size.height;
     if(maximumOffset==currentOffset){
        //加载更多数据
         [self loadData];
    }
}
-(void)loadData{
    _currentPage = _currentPage+1;

    if(_totalPage==0){
       [self searchSceneryByCityID:_currentCityID page:1 pageSize:RecordsOfPage];
    }else if(_currentPage<=_totalPage){
        
        [self searchSceneryByCityID:_currentCityID page:_currentPage pageSize:RecordsOfPage];
    }
    
    
}
-(void)citySelected:(NSString* )cityID  cityName:(NSString*)cityName{
   
    _currentPage=0;
    _totalPage=0;
    [_arrayScenery removeAllObjects];
   // [self.collectionView reloadData];
    
    self.navigationItem.title=cityName;
    _currentCityID=cityID;
    _currentCityName=cityName;
    _appDelegate.currentCityID=cityID;
    _appDelegate.currentCityName=cityName;
    [self loadData];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    LTCityViewController* cityController=(LTCityViewController*)segue.destinationViewController;
    cityController.delegate=self;
    
}
-(void)dealloc{
    adBanner=nil;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
